let fileUrl="";
let baseUrl = "";
const env = "dev";

if (env === "dev") {
	baseUrl = 'http://127.0.0.1:3000' + "/applet";
	fileUrl = "http://192.168.0.108:8001/oss/upload";
} else if (env === "pro") {
	baseUrl = 'https://www.dangxiajing.cn' + "/applet";
	// baseUrl = 'http://127.0.0.1:3000' + "/applet";
	fileUrl = "http://xxx.xxx.xxx.xxx/oss/upload";
}

const request = (url: string, method = 'GET', data = {}, header = {}) => {
	return new Promise((resolve, reject) => {
		header["Authorization"] = uni.getStorageSync("token");
		uni.request({
			url: baseUrl + url,
			method: method,
			data: data,
			header: header,
			success: (res) => {
				if (res.data?.code == 401) {
					uni.reLaunch({
						url: "/pages/login/login"
					})
				}
				resolve(res.data)
			},
			fail: (err: any) => {
				const result = { code: 500, msg: err || "获取数据失败" };
				reject(result)
			}
		})
	})
}

const uploadFile = (filePath: string) => {
	return new Promise((resolve, reject) => {
		let header={};
		header["Authorization"] = uni.getStorageSync("token");
		uni.uploadFile({
			url: fileUrl, //仅为示例，非真实的接口地址
			filePath: filePath,
			name: 'file',
			formData: {
				'user': 'test'
			},
			header: header,
			success: (res) => {
				resolve(JSON.parse(res.data))
			},
			fail: (err: any) => {
				let result = {
					code: 500,
					msg: err || "获取数据失败"
				};
				reject(result)
			}
		});
	})
}

const form = (url: string, param: any) => {
	return request(url, "post", param, { 'Content-Type': 'application/x-www-form-urlencoded' })
}

const post = (url: string, param: any) => {
	return request(url, "post", param, { 'Content-Type': 'application/json' })
}

const get = (url: string, param: any) => {
	return request(url, "get", param, { 'Content-Type': 'application/json' })
}

export default { uploadFile, request, form, post, get };
